<?php

class Application_Model_UserMapper {

    protected $_dbTable;

    public function setDbTable($dbTable) {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable() {
        if (null === $this->_dbTable) {
            $this->setDbTable('Application_Model_DbTable_User');
        }
        return $this->_dbTable;
    }

    public function save(Application_Model_User $user) {
        $data = array(
            'id' => $user->id(),
            'login' => $user->login(),
            'hashedPassword' => $user->hashedPassword(),
            'email' => $user->email(), 
            'activated' => $user->activated(),
            'level' => $user->level(),
            'banned' => $user->banned(),
        );
        if (null === ($id = $user->id())) {
            unset($data['id']);
            return $this->getDbTable()->insert($data);
        } else {
            $this->getDbTable()->update($data, array('id = ?' => $id));
            return $id;
        }
    }

    public function find($id) {
        $result = $this->getDbTable()->find($id);
        if (0 == count($result)) {
            return null;
        }
        $row = $result->current();
        return new Application_Model_User($row->id, $row->login, $row->hashedPassword, $row->email, $row->activated, $row->level, $row->banned);
    }

    public function findByLogin($login) {
        $row = $this->getDbTable()->fetchRow("login = '$login'");
        if ($row === null) {
            return null;
        }
        return new Application_Model_User($row->id, $row->login, $row->hashedPassword, $row->email, $row->activated, $row->level, $row->banned);
    }

    public function fetchAll() {
        $resultSet = $this->getDbTable()->fetchAll();
        $entries = array();
        foreach ($resultSet as $row) {
            $entry = new Application_Model_User($row->id, $row->login, $row->hashedPassword, $row->email, $row->activated, $row->level, $row->banned);
            $entries[] = $entry;
        }
    }

    public function findAllSuperAdmins() {
        $resultSet = $this->getDbTable()->fetchAll("level='superadmin'");
        $entries = array();
        foreach ($resultSet as $row) {
            $entry = new Application_Model_User($row->id, $row->login, $row->hashedPassword, $row->email, $row->activated, $row->level, $row->banned);
            $entries[] = $entry;
        }
        return $entries;
    }
}